import { defineConfig, loadEnv } from "vite";
import { resolve } from "path";
import vue from "@vitejs/plugin-vue";
import svgLoader from "vite-svg-loader";
import Icons from "unplugin-icons/vite";
import IconsResolver from "unplugin-icons/resolver";
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import dts from "vite-plugin-dts";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
const pathResolve = (dir: string): string => {
	return resolve(__dirname, ".", dir);
};

const alias: Record<string, string> = {
	"@": pathResolve("src"),
	"@pkg": pathResolve("pkg"),
};
export default ({ mode }) => {
	const env = loadEnv(mode, process.cwd());
	// https://vitejs.dev/config/
	return defineConfig({
		plugins: [
			vue(),
			svgLoader(),
			AutoImport({
				imports: ["vue"],
				resolvers: [
					ElementPlusResolver(),
					IconsResolver({
						prefix: "Icon",
					}),
				],
				dts: pathResolve("src/auto-imports.d.ts"),
			}),
			Components({
				resolvers: [
					ElementPlusResolver(),
					IconsResolver({
						enabledCollections: ["ep"],
						prefix: false,
						customCollections: [],
					}),
				],
				dts: pathResolve("components.d.ts"),
			}),
			Icons({ autoInstall: true }),
			dts({ rollupTypes: true }),
		],
		resolve: {
			alias,
		},
		css: {
			preprocessorOptions: {
				scss: {
					additionalData: '@import "@/scss/index.scss";',
				},
			},
		},
		server: {
			port: 666,
			host: "0.0.0.0",
			proxy: {
				[`/api`]: {
					target: env.VITE_BASE_URL,
					changeOrigin: true,
					rewrite: path => path.replace(/^\/api/, ""),
				},
			},
		},
		build: {
			lib: {
				entry: resolve(__dirname, "./pkg/index.ts"),
				name: "pkg",
				fileName: format => `pkg-${format}.js`,
			},
			outDir: "dist",
			minify: "terser",

			terserOptions: {
				compress: {
					drop_debugger: true,
					drop_console: true,
				},
			},
			rollupOptions: {
				external: ["vue", "axios"],
				output: {
					exports: "named",
					globals: {
						vue: "Vue",
						axios: "axios",
					},
				},
			},
		},
	});
};
